package com.qiyee.dalligent;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Title: BarcodeGenerator
 * Description:
 * Create on: 2024/12/19 10:14
 *
 * @author xt.ahs.shiyaning1
 * @version 1.0.0
 */
public class BarcodeGenerator {
    public static void generateBarcode(String text, String filePath) {
        try {
            // 创建多格式条码写入器
            MultiFormatWriter writer = new MultiFormatWriter();
            // 生成比特矩阵，文本为条码内容，类型为QR_CODE
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.EAN_13, 100, 50);
            BufferedImage image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_BGR);
            for (int x = 0; x < 100; x++) {
                for (int y = 0; y < 50; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); // 根据比特矩阵设置颜色
                }
            }
            // 保存图像到文件
            ImageIO.write(image, "png", new File(filePath));
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常信息
        }
    }
    public static void exportToExcel(String barcodeFilePath) {
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Barcodes"); // 创建工作表

        Row row = sheet.createRow(0); // 创建第一行
        Cell cell = row.createCell(0); // 创建单元格
        cell.setCellValue("Barcode Image"); // 设置单元格内容

        try {
            // 插入条码图片
            int pictureIndex = workbook.addPicture(Files.readAllBytes(Paths.get(barcodeFilePath)), Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper(); // 创建帮助器
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(0);
            anchor.setRow1(1);
            drawing.createPicture(anchor, pictureIndex).resize(); // 设置图片大小

            // 保存Excel文件
            try (FileOutputStream outputStream = new FileOutputStream("Barcodes.xlsx")) {
                workbook.write(outputStream);
            }
            workbook.close(); // 关闭工作簿
        } catch (IOException e) {
            e.printStackTrace(); // 输出异常信息
        }
    }
    public static void main(String[] args) {
        String barcodeText = "123456789zzz"; // 条码内容
        String barcodeFilePath = "barcode.png"; // 条码图片路径

        // 生成条码
        BarcodeGenerator.generateBarcode(barcodeText, barcodeFilePath);

        // 导出到Excel
        exportToExcel(barcodeFilePath);

        System.out.println("条码生成并导出到Excel成功！");
    }


}
